import { createSlice, createAsyncThunk } from '@reduxjs/toolkit';
import { bookingAPI } from '../../services/api';

// 异步thunks - 基于新的预订管理接口
export const createBooking = createAsyncThunk(
  'booking/createBooking',
  async (bookingData, { rejectWithValue }) => {
    try {
      const response = await bookingAPI.createBooking(bookingData);
      return response.data;
    } catch (error) {
      return rejectWithValue(error.response?.data?.message || '创建预订失败');
    }
  }
);

export const fetchBookings = createAsyncThunk(
  'booking/fetchBookings',
  async (params = {}, { rejectWithValue }) => {
    try {
      const response = await bookingAPI.getAllBookings(params);
      return response.data;
    } catch (error) {
      return rejectWithValue(error.response?.data?.message || '获取预订列表失败');
    }
  }
);

export const fetchBookingByNumber = createAsyncThunk(
  'booking/fetchBookingByNumber',
  async (bookingNumber, { rejectWithValue }) => {
    try {
      const response = await bookingAPI.getBookingByNumber(bookingNumber);
      return response.data;
    } catch (error) {
      return rejectWithValue(error.response?.data?.message || '获取预订详情失败');
    }
  }
);

export const fetchPassengerBookings = createAsyncThunk(
  'booking/fetchPassengerBookings',
  async (passengerId, { rejectWithValue }) => {
    try {
      const response = await bookingAPI.getPassengerBookings(passengerId);
      return response.data;
    } catch (error) {
      return rejectWithValue(error.response?.data?.message || '获取乘客预订失败');
    }
  }
);

export const cancelBooking = createAsyncThunk(
  'booking/cancelBooking',
  async (bookingNumber, { rejectWithValue }) => {
    try {
      const response = await bookingAPI.cancelBooking(bookingNumber);
      return response.data;
    } catch (error) {
      return rejectWithValue(error.response?.data?.message || '取消预订失败');
    }
  }
);

export const updateBookingSeat = createAsyncThunk(
  'booking/updateBookingSeat',
  async ({ bookingNumber, seatData }, { rejectWithValue }) => {
    try {
      const response = await bookingAPI.updateBookingSeat(bookingNumber, seatData);
      return response.data;
    } catch (error) {
      return rejectWithValue(error.response?.data?.message || '更新座位失败');
    }
  }
);

export const getAvailableSeats = createAsyncThunk(
  'booking/getAvailableSeats',
  async (flightId, { rejectWithValue }) => {
    try {
      const response = await bookingAPI.getAvailableSeats(flightId);
      return response.data;
    } catch (error) {
      return rejectWithValue(error.response?.data?.message || '获取可用座位失败');
    }
  }
);

export const searchBookings = createAsyncThunk(
  'booking/searchBookings',
  async ({ booking_number, passenger_name, flight_number }, { rejectWithValue }) => {
    try {
      const params = {};
      if (booking_number) params.booking_number = booking_number;
      if (passenger_name) params.passenger_name = passenger_name;
      if (flight_number) params.flight_number = flight_number;
      
      const response = await bookingAPI.searchBookings(params);
      return response.data;
    } catch (error) {
      return rejectWithValue(error.response?.data?.message || '搜索预订失败');
    }
  }
);

const bookingSlice = createSlice({
  name: 'booking',
  initialState: {
    bookings: [],
    currentBooking: null,
    availableSeats: [],
    loading: false,
    error: null,
    pagination: {
      current: 1,
      pageSize: 10,
      total: 0,
    },
  },
  reducers: {
    clearCurrentBooking: (state) => {
      state.currentBooking = null;
    },
    clearError: (state) => {
      state.error = null;
    },
    setPagination: (state, action) => {
      state.pagination = { ...state.pagination, ...action.payload };
    },
  },
  extraReducers: (builder) => {
    builder
      // 创建预订
      .addCase(createBooking.pending, (state) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(createBooking.fulfilled, (state, action) => {
        state.loading = false;
        state.currentBooking = action.payload;
      })
      .addCase(createBooking.rejected, (state, action) => {
        state.loading = false;
        state.error = action.payload;
      })
      // 获取预订列表
      .addCase(fetchBookings.pending, (state) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(fetchBookings.fulfilled, (state, action) => {
        state.loading = false;
        state.bookings = action.payload.bookings || action.payload;
        state.pagination.total = action.payload.total || action.payload.length;
      })
      .addCase(fetchBookings.rejected, (state, action) => {
        state.loading = false;
        state.error = action.payload;
      })
      // 获取预订详情
      .addCase(fetchBookingByNumber.pending, (state) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(fetchBookingByNumber.fulfilled, (state, action) => {
        state.loading = false;
        state.currentBooking = action.payload;
      })
      .addCase(fetchBookingByNumber.rejected, (state, action) => {
        state.loading = false;
        state.error = action.payload;
      })
      // 获取乘客预订
      .addCase(fetchPassengerBookings.pending, (state) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(fetchPassengerBookings.fulfilled, (state, action) => {
        state.loading = false;
        state.bookings = action.payload;
      })
      .addCase(fetchPassengerBookings.rejected, (state, action) => {
        state.loading = false;
        state.error = action.payload;
      })
      // 取消预订
      .addCase(cancelBooking.pending, (state) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(cancelBooking.fulfilled, (state, action) => {
        state.loading = false;
        if (state.currentBooking?.booking_number === action.payload.booking_number) {
          state.currentBooking = action.payload;
        }
        const index = state.bookings.findIndex(b => b.booking_number === action.payload.booking_number);
        if (index !== -1) {
          state.bookings[index] = action.payload;
        }
      })
      .addCase(cancelBooking.rejected, (state, action) => {
        state.loading = false;
        state.error = action.payload;
      })
      // 获取可用座位
      .addCase(getAvailableSeats.pending, (state) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(getAvailableSeats.fulfilled, (state, action) => {
        state.loading = false;
        state.availableSeats = action.payload;
      })
      .addCase(getAvailableSeats.rejected, (state, action) => {
        state.loading = false;
        state.error = action.payload;
      })
      // 搜索预订
      .addCase(searchBookings.pending, (state) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(searchBookings.fulfilled, (state, action) => {
        state.loading = false;
        state.bookings = action.payload;
      })
      .addCase(searchBookings.rejected, (state, action) => {
        state.loading = false;
        state.error = action.payload;
      });
  },
});

export const { clearCurrentBooking, clearError, setPagination } = bookingSlice.actions;
export default bookingSlice.reducer;